package com.vrv.app.cyberspace.modules.sys.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.vrv.app.cyberspace.common.ddio.AllOrgResult;
import com.vrv.app.cyberspace.common.ddio.ApiV2Service;
import com.vrv.app.cyberspace.common.utils.JSONResult;
import com.vrv.app.cyberspace.modules.sys.entity.OrganizeTable;
import com.vrv.app.cyberspace.modules.sys.mapper.OrganizeTableMapper;
import com.vrv.app.cyberspace.modules.sys.service.IOrganizeTableService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author sm
 * @since 2017-12-28
 */
@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@Service
public class OrganizeTableServiceImpl extends ServiceImpl<OrganizeTableMapper, OrganizeTable> implements IOrganizeTableService {
    Logger logger = LoggerFactory.getLogger(OrganizeTableServiceImpl.class);

    @Autowired
    private OrganizeTableMapper organizeTableMapper;
    @Autowired
    private ApiV2Service apiV2Service;

    @Override
    @Transactional
    public void synchDDIOOrg() {
        String result = apiV2Service.getAllOrg();
        logger.info(result);
        AllOrgResult allOrgResult = JSON.parseObject(result, AllOrgResult.class);
        if (allOrgResult.getCode() == 0 && !CollectionUtils.isEmpty(allOrgResult.getOrgList())) {
            for (OrganizeTable o : allOrgResult.getOrgList()) {
                o.setCreationDate(new Date());
                o.setUpdatedDate(new Date());
                if (organizeTableMapper.selectById(o.getOrgID()) != null) {
                    organizeTableMapper.updateById(o);
                } else {
                    organizeTableMapper.insert(o);
                }
            }
        }
    }


    @Override
    public JSONResult listOffices(Integer id) {
        List<OrganizeTable> listOff = organizeTableMapper.listOffices(id);
        return JSONResult.renderSuccess(listOff);
    }

    @Override
    public JSONResult listOperators(Integer id) {
        List<OrganizeTable> listOper = organizeTableMapper.listOperators(id);
        return JSONResult.renderSuccess(listOper);
    }

    @Override
    public JSONResult dailyOrgs() {
        return JSONResult.renderSuccess(organizeTableMapper.selectList(new EntityWrapper<OrganizeTable>()
                .in("roleID", new Integer[]{3, 4})
                .ne("parentOrgID", 0)));
    }
}
